#!/bin/bash

# 人脸检测系统启动脚本
# 作者: fsserver
# 日期: 2024-01-01

APP_NAME="face-detection-system"
APP_VERSION="1.0.0"
JAR_FILE="${APP_NAME}-${APP_VERSION}.jar"
PID_FILE="${APP_NAME}.pid"
LOG_FILE="logs/startup.log"

# 创建日志目录
mkdir -p logs

# 检查Java环境
if ! command -v java &> /dev/null; then
    echo "错误: 未找到Java运行环境，请安装JDK 8或更高版本"
    exit 1
fi

# 检查Java版本
JAVA_VERSION=$(java -version 2>&1 | awk -F '"' '/version/ {print $2}' | awk -F '.' '{print $1$2}')
if [ "$JAVA_VERSION" -lt 18 ]; then
    echo "错误: Java版本过低，需要JDK 8或更高版本"
    exit 1
fi

# 检查JAR文件是否存在
if [ ! -f "$JAR_FILE" ]; then
    echo "错误: 找不到JAR文件 $JAR_FILE"
    echo "请先执行 mvn clean package 构建项目"
    exit 1
fi

# 检查是否已经运行
if [ -f "$PID_FILE" ]; then
    PID=$(cat "$PID_FILE")
    if ps -p "$PID" > /dev/null 2>&1; then
        echo "应用已经在运行中，PID: $PID"
        exit 1
    else
        echo "删除过期的PID文件"
        rm -f "$PID_FILE"
    fi
fi

# 设置JVM参数
JVM_OPTS="-Xms512m -Xmx2g"
JVM_OPTS="$JVM_OPTS -XX:+UseG1GC"
JVM_OPTS="$JVM_OPTS -XX:MaxGCPauseMillis=200"
JVM_OPTS="$JVM_OPTS -XX:+PrintGCDetails"
JVM_OPTS="$JVM_OPTS -XX:+PrintGCTimeStamps"
JVM_OPTS="$JVM_OPTS -Xloggc:logs/gc.log"
JVM_OPTS="$JVM_OPTS -XX:+UseGCLogFileRotation"
JVM_OPTS="$JVM_OPTS -XX:NumberOfGCLogFiles=5"
JVM_OPTS="$JVM_OPTS -XX:GCLogFileSize=10M"

# 设置应用参数
APP_OPTS="--spring.profiles.active=pro"
APP_OPTS="$APP_OPTS --server.port=8080"

# 启动应用
echo "正在启动 $APP_NAME..."
echo "JAR文件: $JAR_FILE"
echo "JVM参数: $JVM_OPTS"
echo "应用参数: $APP_OPTS"

nohup java $JVM_OPTS -jar "$JAR_FILE" $APP_OPTS > "$LOG_FILE" 2>&1 &
PID=$!

# 保存PID
echo $PID > "$PID_FILE"

# 等待启动
sleep 3

# 检查启动状态
if ps -p "$PID" > /dev/null 2>&1; then
    echo "启动成功！"
    echo "PID: $PID"
    echo "日志文件: $LOG_FILE"
    echo "API文档: http://localhost:8080/face-detection/doc.html"
    echo "健康检查: http://localhost:8080/face-detection/api/face/health"
else
    echo "启动失败，请检查日志文件: $LOG_FILE"
    rm -f "$PID_FILE"
    exit 1
fi 